package com.mk.seckill.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mk.seckill.pojo.User;
import com.mk.seckill.service.IUserService;
import com.mk.seckill.utils.CookieUtil;
import com.mk.seckill.vo.RespBean;
import com.mk.seckill.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class AccessLimitInterceptor implements HandlerInterceptor {
    /**
     * @Author hhwu
     * @Description //TODO 拦截器
     * @Date 19:32 2022/6/13
     **/

    @Autowired
    private IUserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * @Author hhwu
         * @Description //TODO 配置指定AccessLimit注解的方法的拦截规则：对该方法使用计数器算法限流。并且将当前线程的登录user设置到threadlocal中
         * @Date 20:46 2022/6/13
         * @Param [request, response, handler]
         * @return boolean
         **/
        if (handler instanceof HandlerMethod) {// 如果被处理的对象时方法
            // 将当前登录的用户信息写入threadlocal中
            User user = getUser(request, response);
            UserContext.setUser(user);

            //获取方法上的注解
            HandlerMethod hm = (HandlerMethod) handler;
            AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
            if (accessLimit == null) {// 该方法上没有@AccessLimit注解时
                return true;
            }

            // 处理被@AccessLimit注解的方法
            int second = accessLimit.second();
            int maxCount = accessLimit.maxCount();
            boolean needLogin = accessLimit.needLogin();
            String key = request.getRequestURI();
            if (needLogin) {// 如果被@AccessLimit注解的方法需要登录才能访问
                if (user == null) {
                    render(response, RespBeanEnum.SESSION_ERROR);
                }
                key += ":" + user.getId();
            }

            // 对@AccessLimit注解的方法限流，在规定周期内现在访问次数
            ValueOperations valueOperations = redisTemplate.opsForValue();
            Integer count = (Integer) valueOperations.get(key);
            if (count == null) {
                valueOperations.set(key, 1, second, TimeUnit.SECONDS);
            } else if (count < maxCount) {
                valueOperations.increment(key);
            } else {
                render(response, RespBeanEnum.ACCESS_LIMIT_REACHED);
                return false;
            }
        }

        return true;// 放行
    }

    private void render(HttpServletResponse response, RespBeanEnum respBeanEnum) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter printWriter = response.getWriter();
        RespBean bean = RespBean.error(respBeanEnum);
        printWriter.write(new ObjectMapper().writeValueAsString(bean));
        printWriter.flush();
        printWriter.close();
    }

    private User getUser(HttpServletRequest request, HttpServletResponse response) {
        /**
         * @Author hhwu
         * @Description //TODO 判断用户是否存在的逻辑，返回用户对象
         * @Date 20:31 2022/6/13
         * @Param [request, response]
         * @return com.mk.seckill.pojo.User
         **/
        String userTicket = CookieUtil.getCookieValue(request, "userTicket");
        if (StringUtils.isEmpty(userTicket)) {
            return null;
        }
        return userService.getUserByCookie(userTicket, request, response);
    }
}
